<?php
/**
 * Created by PhpStorm.
 * User: Allen
 * Date: 2017/1/17
 * Time: 17:08
 */

namespace EWeiLink\JuPai\Services;


use Illuminate\Support\Facades\Redis;

class SupportService
{
    /**
     *
     * @FunName: createAccessToken
     * @Param: * @param $user(实例)
     * @param $prefix
     */
    public function createAccessToken($user, $prefix, $filter) {

        $user_id = $user->_id;
        $key = $prefix.$user_id;

        // 如果传递要刷新的参数  refresh = true; 则重新创建，并缓存到redis中
        $refresh = array_get($filter, 'refresh', false);
        if ($refresh === true) {
            $tokenResult  = $user->createToken('jp');
            $accessToken = $tokenResult->accessToken;
            $token = $tokenResult->token;
            $token_array = $token->getAttributes();
            $date = array_get($token_array, 'expires_at.date');
            $expireTime = strtotime($date);
            // 缓存到redis
            Redis::set($key, $accessToken);
            // 设置过期时间
            Redis::expire($key, $expireTime);

            return $accessToken;
        }

        // 先从redis中拿
        $accessToken = Redis::get($key);
        if (is_null($accessToken)) {
            $tokenResult  = $user->createToken('jp');
            $accessToken = $tokenResult->accessToken;
            $token = $tokenResult->token;
            $token_array = $token->getAttributes();
            $date = array_get($token_array, 'expires_at.date');
            $expireTime = strtotime($date);
            // 缓存到redis
            Redis::set($key, $accessToken);
            // 设置过期时间
            Redis::expire($key, $expireTime);
        }

        return $accessToken;
    }
    
}
